package chapter04

import scala.collection.immutable

object Demo02_ForLoop {
  def main(args: Array[String]): Unit = {
    //java中 for语法： for(int i = 0 ; i < 10 ; i++ ){System.out.println(i + ". hello word );

    //遍历范围
    for (i <- 1 to 10){  //本质是to方法的方法调用
      println(i + ". hello word")
    }

    for (i <- 1 until 10) {  //不包括最后一个数字（范围遍历）
      println(i + ".hello word")
    }

    //遍历元素  集合遍历
    for (i <- Array(12,35,88)){
      println(i)
    }

    for (i <- List(12,35,88)){
      println(i)
    }

    for (i <- Set(12,35,88)){
      println(i)
    }

    println("==============================")
    //循环守卫 ， 循环保护式
    for (i <- 1 to 10 if i != 5 ){
      print(i)
    }
    println()
    println("==============================")
    //循环步长  指定步长为2每隔两个取一个数
    for (i <- 1 to 10 by 2){
      print(i)
    }
    println()
    println("------------------------------")
    for (i <- 13 to 30 by 3){
      print(i)
    }
    println()
    println("------------------------------")
    for (i <- 10 to 1 by -1 ){
      print(i)
    }
    println()
    println("------------------------------")
    for (i <- 10 to 1 reverse ){
      print(i)
    }
    //步长不可以为0，可以为浮点型  推荐使用BigDecimal这样可以保证精度
    //for (i <- 1 to 10 by 0.5)
    for (i <- 1.0 to 10.0 by 0.5){
      print(i)
    }

    println("==============================")
    //嵌套循环
    for (i <- 1 to 3 ){
      for(j <- 1 to 3){
        print("i = " + i + ", j =" + j)
      }
    }
    println()
    println("------------------------")
    for (i <- 1 to 3; j <- 1 to 5){
      println("i=" + i + ", j=" + j)
    }
    println("================================")
    //循环返回值
    //默认返回值为空值
    val a: Unit = for (i <- 1 to 10) {
      i
    }
    println("a = " + a)  //a = ()

    val ints: immutable.IndexedSeq[Int] = for (i <- 1 to 10) yield i
    println(ints) //Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)






  }

}
